/**
 * Created with IntelliJ IDEA.
 * Description: leetcode: 151. 反转字符串中的单词
 * <a href="https://leetcode.cn/problems/reverse-words-in-a-string/">...</a>
 * User: DELL
 * Date: 2023-10-14
 * Time: 23:23
 */
public class Solution {
    /**
     * 解题思路:
     * 从后往前遍历原字符串 s,同时使用 StringBuilder 来依次拼接每一个
     * 单词,同时拼接每一个单词后,均加上空格,最后将最末尾的空格去掉即可.
     *
     * @param s
     * @return
     */
    public String reverseWords(String s) {
        // 题目保证输入字符串长度大于 1,因此不用进行非空校验
        StringBuilder builder = new StringBuilder();
        int len = s.length();
        for (int i = len - 1; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                int j = i - 1;
                while (j >= 0 && s.charAt(j) != ' ') {
                    j--;
                }
                builder.append(s, j + 1, i + 1);
                builder.append(' ');
                i = j;
            }
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String temp = "the sky is blue";
        System.out.println(solution.reverseWords(temp));
    }
}